import { isNullOrWhitespace } from '@/utils'

const ACTIONS = {
  view: '查看',
  edit: '编辑',
  add: '新增',
}

export default function ({
  name,
  initForm = {},
  doCreate,
  doDelete,
  doUpdate,
  doError,
  refresh,
}) {
  const modalVisible = ref(false)
  const modalAction = ref('')
  const modalTitle = computed(() => ACTIONS[modalAction.value] + name)
  const modalLoading = ref(false)
  const modalFormRef = ref(null)
  const modalForm = ref({ ...initForm })

  // 自定义参数
  let customParamsFn = () => {}

  /** 新增 */
  function handleAdd(extraParams = {}, customParams = () => {}) {
    modalAction.value = 'add'
    modalVisible.value = true
    modalForm.value = { ...initForm, ...extraParams }
    customParamsFn = customParams
  }

  /** 修改 */
  function handleEdit(row = {}, extraParams = {}, customParams = () => {}) {
    modalAction.value = 'edit'
    modalVisible.value = true
    modalForm.value = { ...row, ...extraParams }
    customParamsFn = customParams
  }

  /** 查看 */
  function handleView(row = {}) {
    modalAction.value = 'view'
    modalVisible.value = true
    modalForm.value = { ...row }
  }

  /** 保存 */
  function handleSave() {
    let realModalFormRef = null
    let isArray = false

    if (modalFormRef.value?.modalFormRef) {
      realModalFormRef = modalFormRef.value.modalFormRef
      isArray = Array.isArray(modalFormRef.value.modalFormRef)
    } else {
      realModalFormRef = modalFormRef.value
    }

    if (!['edit', 'add'].includes(modalAction.value)) {
      modalVisible.value = false
      return
    }

    if (isArray) {
      let totalCount = 0
      let passCount = 0

      realModalFormRef.map((v) => {
        v?.validate(async (err) => {
          totalCount += 1

          if (!err) {
            passCount += 1
          }

          if (totalCount === realModalFormRef.length) {
            if (passCount === realModalFormRef.length) {
              $message.success('验证通过')
            } else {
              $message.error('请检查每个Tab的表单都填写完整')
            }
          }
        })
      })
    } else {
      realModalFormRef?.validate(async (err) => {
        if (err) return
        const actions = {
          add: {
            api: () =>
              doCreate({
                ...modalForm.value,
                ...customParamsFn(modalForm.value),
              }),
            cb: () => $message.success('新增成功'),
          },
          edit: {
            api: () =>
              doUpdate({
                ...modalForm.value,
                ...customParamsFn(modalForm.value),
              }),
            cb: () => $message.success('编辑成功'),
          },
        }

        const action = actions[modalAction.value]

        try {
          modalLoading.value = true
          const { code, data1, data2 } = await action.api()
          if (code === 200) {
            refresh(data1, data2)
            action.cb()
            modalLoading.value = false
            modalVisible.value = false
          } else {
            doError(modalAction.value, data1, data2)
            modalLoading.value = false
          }
        } catch (error) {
          modalLoading.value = false
        }
      })
    }
  }

  /** 删除 */
  function handleDelete(params, confirmOptions) {
    $dialog.confirm({
      type: 'error',
      title: '消息提示',
      content: '确定删除？',
      async confirm() {
        try {
          modalLoading.value = true
          const { code, data1, data2 } = await doDelete(params)
          if (code === 200) {
            refresh(data1, data2)
            $message.success('删除成功')
            modalLoading.value = false
          } else {
            doError('del', data1, data2)
            modalLoading.value = false
          }
        } catch (error) {
          modalLoading.value = false
        }
      },
      ...confirmOptions,
    })
  }

  return {
    modalVisible,
    modalAction,
    modalTitle,
    modalLoading,
    handleAdd,
    handleDelete,
    handleEdit,
    handleView,
    handleSave,
    modalForm,
    modalFormRef,
  }
}
